<template>
  <el-dialog :title="$attrs.dialogType=='add'?`新建角色`:`编辑角色`" :visible.sync="$attrs.visableIf" top="60px" @close="handleCloseDialog" :close-on-click-modal="false" :close-on-press-escape="false" append-to-body width="700px">
    <el-form :model="queryParams" ref="queryForm" :rules="rules" size="small" :inline="true" label-width="120px">
      <el-form-item label="角色名称：" prop="roleName">
        <el-input v-model="queryParams.roleName" placeholder="请输入角色名称，10字以内" maxlength="10" minlength="1" show-word-limit></el-input>
      </el-form-item>
      <el-form-item label="排序号" prop="roleSort">
        <el-input-number v-model="queryParams.roleSort" controls-position="right" :min="1"/>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="queryParams.status">
          <el-radio
            v-for="item in visibleList"
            :key="Number(item.value)"
            :label="item.value"
          >{{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="菜单权限">
        <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event)">展开/折叠</el-checkbox>
        <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event)">全选/全不选</el-checkbox>
        <el-checkbox v-model="menuCheckStrictly" @change="handleCheckedTreeConnect($event)" disabled>父子联动</el-checkbox>
        <el-tree
          class="tree-border"
          :data="treeData"
          show-checkbox
          ref="menu"
          node-key="id"
          :check-strictly="!menuCheckStrictly"
          empty-text="加载中，请稍候"
          :show-count="true"
          :props="defaultProps"
        ></el-tree>
      </el-form-item>
      <el-form-item label="备注：" prop="remark">
        <el-input v-model="queryParams.remark" placeholder="请输入备注" type="textarea" maxlength="80" minlength="1" show-word-limit></el-input>
      </el-form-item>

    </el-form>
    <span slot="footer" class="dialog-footer">
    <el-button @click="handleCloseDialog">取 消</el-button>
    <el-button type="primary" @click="onSubmit('queryForm')">确 定</el-button>
  </span>
  </el-dialog>
</template>

<script>
import {reqRoleAllMenu, reqAddRole, reqEditRole, reqGetRoleInfo, reqGetRoleMenuList} from '@/api/roles'

export default {
  name: 'addOrEditRole',
  data() {
    return {
      menuExpand: false,
      menuNodeAll: false,
      menuCheckStrictly: true,
      visibleList: [
        {value: 0, label: '显示'},
        {value: 1, label: '隐藏'}
      ],
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },

      total: 8,// 表格的总条数
      queryParams: {
        roleName: null,//角色名称
        menuIds: [],//角色菜单id集合
        roleSort: 1,//角色排序
        remark: '',//备注
        status: 0//显示状态
      },
      rules: {
        'roleName': [
          {required: true, message: '请输入角色名称', trigger: 'blur'}
        ],
        'roleSort': [
          {required: true, message: '请选择角色排序', trigger: 'blur'}
        ]
      }
    }
  },
  created() {
    this.getTreeData();//获取所有菜单
  },
  methods: {
    getRoleInfoById() {
      reqGetRoleInfo(this.$attrs.id).then(res => {
        console.log('获取详情', res.data)
        this.queryParams = res.data
      })
    },
    getRoleMenuList() {
      reqGetRoleMenuList(this.$attrs.id).then(res => {
        let data = res.data.checkedKeys;
        console.log('接口调用权限', data);
        data.forEach(item => {
          this.$nextTick(()=>{
            this.$refs.menu.setChecked(item, true, false)
          })

        })

      })
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value) {
      let treeList = this.treeData
      for (let i = 0; i < treeList.length; i++) {
        this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value) {
      this.$refs.menu.setCheckedNodes(value ? this.treeData : [])

    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value) {
      this.menuCheckStrictly = value ? true : false
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys()
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    getTreeData() {
      reqRoleAllMenu().then(res => {
        this.treeData = res.data
        console.log('获取所有菜单', res);
        if (this.$attrs.id) {
          this.getRoleMenuList();
          this.getRoleInfoById();//获取详情
        }
        //下面是自定义角色的回显
        if (this.$attrs.pageType == 1 && this.$attrs.dialogType == 'edit') {
          //自定义角色的时候赋值
          this.queryParams = this.$attrs.roleInfo;
          let menuIds = this.queryParams.menuIds;
          console.log('编辑获取的角色信息', this.$attrs.roleInfo);
          console.log('角色权限', menuIds);
          if (menuIds && menuIds.length > 0) {
            menuIds.forEach(item => {
              this.$nextTick(()=>{
                this.$refs.menu.setChecked(item, true, false);
              })

            });
          }

        }
      })
    },
    onSubmit(formName) {
      //提交的代码
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.queryParams.menuIds = this.getMenuAllCheckedKeys();
          if (this.$attrs.pageType == 2) {
            let axiosUrl = ''
            if (this.$attrs.dialogType == `add`) {
              //调用添加接口
              axiosUrl = reqAddRole
            } else {
              //调用编辑接口
              this.queryParams.id = this.$attrs.id;
              axiosUrl = reqEditRole
            }
            console.log('axiosUrl', axiosUrl)
            axiosUrl(this.queryParams).then(res => {
              this.$modal.msgSuccess('操作成功！')
              this.handleCloseDialog()//关闭窗口
              this.$emit('getList')
            })
          } else {
            //协作者新增页面的方法
            this.$emit('getFormInfo', this.queryParams);
            this.handleCloseDialog()//关闭窗口
          }


        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleCloseDialog() {
      this.$emit('update:visableIf', false)
      this.$emit('handleCloseFilter') //关闭弹窗;
    }
  }
}
</script>

<style scoped lang="scss">
.el-form {
  display: flex;
  flex-direction: column;

  ::v-deep .el-form-item {
    display: flex;

    .el-form-item__content {
      flex: 1;
    }
  }

}

.tree-border {
  width: 400px;
}
</style>
